/**
 * a script for the timeline jsp
 */
$(document).ready(function(){
	
	var username = $(".username").attr('id');
	$(".loader").show();
	
	//default 1 while loading the page
	 $.ajax({
		  url:"/salonmorandsmigi/FeatureServlet?action=timeline&xsl=1&username="+username,
		  type: "GET",
		  success: function(data,status,xhr){
			   $(".timeline").html(xhr.responseText);
			   $(".loader").hide();
		  },
		  error: function(){
			 $(".timeline").html("Server Error! try again later.")
			 $(".loader").hide();
		   }
		 });
	 
	//button clicks to change between defaults 1 and 2	
	$("button",".defaultbuttons").button();
	$("button",".defaultbuttons").click(function(){
		$(".timeline").html("");
		var xsl=1;
		if (this.id=="switch2"){
			xsl=2;
		}
		$(".loader").show();
		$.ajax({
			   url:"/salonmorandsmigi/FeatureServlet?action=timeline&xsl="+xsl+"&username="+username,
			   type: "GET",
			   success: function(data,status,xhr){
				   $(".timeline").html(xhr.responseText);
				   $(".loader").hide();
			   },
			   error: function(){
				 $(".submit").append("<div class=\"fail\">FAIL! server error! try again<\div>");
   	 			 setTimeout("$(\".fail\").remove();",2000);
				 $(".timeline").html("Server Error! try again later.")  
				 $(".loader").hide();
			   }
			 });
	});
	
	//form validation and submission with uploaded xsl 
	var options = {
			 url:"/salonmorandsmigi/FeatureServlet?action=timeline&username="+username, 
	    	 type: "GET",
			 beforeSubmit: validator,
	    	 success:function(data,status,xhr) { 
    		 			$(".timeline").html(xhr.responseText);
    		 			$(".loader").hide();
    	 				},
		     statusCode: {
		    	 			400: function() {
			    	 			$(".submit").append("<div class=\"fail\">FAIL! xsl wasn't a valid one!<\div>");
			    	 			setTimeout("$(\".fail\").remove();",2000);
			    	 			$(".loader").hide();
		    	 			},
	    	 				500: function() {
	    	 					$(".submit").append("<div class=\"fail\">FAIL! server error! try again!<\div>");
			    	 			setTimeout("$(\".fail\").remove();",2000);
			    	 			$(".loader").hide();
	    	 				}
		     }
	      }; 
	$("#xslupload").validate({
		rules: {
			xsl: {
				required: true
			}
		},
		messages: {
			xsl: {
				required: "you must give a valid XSL for timeline"
			}
		},
		submitHandler: function(form) {
			$(".timeline").html("");
			$(".loader").show();
		   	$(form).ajaxSubmit(options);
		   }
	});
	
	//validator function for ajax
	function validator() {
		  return $("#xslupload").validate().form;
	  }
	
});